<?php
/**
 * Created by PhpStorm.
 * User: jksen
 * Date: 2018/1/26
 * Time: 下午3:22
 */

namespace app\common\Utils;

use OSS\OssClient;

class Oss
{

    public $config;

    /**
     *
     */
    public static function createPolicy($dir)
    {
        $a = self::checkIsUsefulDir($dir);
        if (!$a) {
            return [
                'code' => '1',
                'msg' => '无效目录'
            ];
        }
        $id = config('param')['oss']['AccessKeyId'];
        $key = config('param')['oss']['AccessKeySecret'];
        $host = config('param')['oss']['ossServer'];
        $callbackUrl = "https://dev-center.ishaohuo.cn/open/index/ossAuth";

        $callback_param = array(
            'callbackUrl' => $callbackUrl,
            'callbackHost' =>"dev-center.ishaohuo.cn",
            'callbackBody' => 'filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}',
            'callbackBodyType' => "application/x-www-form-urlencoded");
        $callback_string = json_encode($callback_param);

        $base64_callback_body = base64_encode($callback_string);
        $now = time();
        $expire = config('param')['oss']['expire']; //设置该policy超时时间是10s. 即这个policy过了这个有效时间，将不能访问
        $end = $now + $expire;

        $expiration = gmt_iso8601($end);


        //最大文件大小.用户可以自己设置
        $condition = array(0 => 'content-length-range', 1 => 0, 2 => 1048576000);
        $conditions[] = $condition;

        //表示用户上传的数据,必须是以$dir开始, 不然上传会失败,这一步不是必须项,只是为了安全起见,防止用户通过policy上传到别人的目录
        $start = array(0 => 'starts-with', 1 => '$key', 2 => $dir);
        $conditions[] = $start;


        $arr = array('expiration' => $expiration, 'conditions' => $conditions);
        //echo json_encode($arr);
        //return;
        $policy = json_encode($arr);
        $base64_policy = base64_encode($policy);
        $string_to_sign = $base64_policy;
        $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $key, true));

        $response = array();
        $response['accessid'] = $id;
        $response['host'] = $host;
        $response['policy'] = $base64_policy;
        $response['signature'] = $signature;
        $response['expire'] = $end;
        $response['callback'] = $base64_callback_body;
        //这个参数是设置用户上传指定的前缀
        $response['dir'] = $dir;
        return $response;
    }

    /**
     *
     * @param $dir
     * @return bool
     * @throws \OSS\Core\OssException
     */
    public static function checkIsUsefulDir($dir)
    {
        $dirlist = [];
        $ossclient = new OssClient(config('param')['oss']['AccessKeyId'], config('param')['oss']['AccessKeySecret'], config('param')['oss']['endpoint']);
        $a = $ossclient->listObjects('fileishaohuo')->getPrefixList();
        if (!empty($a)) {
            foreach ($a as $va) {
                array_push($dirlist, $va->getPrefix());
            }
            return in_array($dir, $dirlist) ? true : false;
        }
        return false;
    }
}